package com.bona.service.system;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bona.dao.common.BaseDao;
import com.bona.dao.system.SysOrgDao;
import com.bona.dao.system.SysUserOrgDao;
import com.bona.model.system.SysOrgModel;
import com.bona.model.system.SysUserOrgModel;
import com.bona.service.common.BaseService;
import com.bona.util.common.StringUtil;
import com.bona.util.common.UUIDGenerator;

/**
 * 
 * <br>
 * <b>功能：</b>SysDepartService<br>
 * <b>作者：</b>tbzeng<br>
 * <b>日期：</b> Dec 9, 2015 <br>
 * <b>版权所有：<b>版权所有(C) 2015，tbzeng<br>
 */
@Service("departService")
@Transactional
public class SysOrgService extends BaseService {
	
	private final static Logger logger = Logger.getLogger(SysOrgService.class);
	
	@Autowired
	private SysOrgDao orgDao;
	@Autowired
	private SysUserOrgDao userOrgDao;
	
	/**
	 * 添加部门
	 * @param model
	 * @return
	 */
	public void add(SysOrgModel model) {
		
		String id = model.getId();
		if (StringUtil.isEmpty(id)) { // 新增
			model.setId(UUIDGenerator.generate());
			orgDao.add(model);
		} else { // 更新
			orgDao.update(model);
		}
	}
	
	/**
	 * 获取最大机构代码
	 * @param orgCode
	 * @param localCodeLen
	 * @return
	 */
	public String queryMaxOrgCode(String orgCode, int localCodeLen) {
		
		String maxOrgCode = orgDao.queryMaxOrgCode(orgCode, localCodeLen);
		return maxOrgCode;
	}
	
	/**
	 * 解除用户机构关联关系
	 * @param model
	 */
	public void deleteUserOrg(SysUserOrgModel model) {
		
		String userids = model.getUserId();
		String orgids = model.getOrgId();
		logger.info("delete user org relation: ["+userids+","+orgids+"]");
		if (StringUtil.isEmpty(userids) || StringUtil.isEmpty(orgids)) {
			return;
		}
		for (String userid: userids.split(",")) {
			for (String orgid: orgids.split(",")) {
				model = new SysUserOrgModel(userid, orgid);
				userOrgDao.delete(model);
			}
		}
	}
	
	/**
	 * 通过机构编号获取机构
	 * @param ids
	 * @return
	 */
	public List<SysOrgModel> queryOrgByIds(List<String> ids) {
		
		 List<SysOrgModel> models = orgDao.queryOrgByIds(ids);
		 return models;
	}
	
	@Override
	public BaseDao getDao() {
		return orgDao;
	}

}
